<?php
class BaseType{
	var $name = "";
	var $template = "ctype/views/types/general.php";
	var $properties = array();
	var $definition = array();
	var $typeElements = array();
	
	var $ci;
	
	/*
	 * Contenido estatico asociado
	 */
	var $static = array(
		"javascript" => array(
		),
		"style" => array(
		)		
	);
	/*
	 * Campos
	 */
	var $fields;
	
	function BaseType(){
		$this->name = strtolower(get_class($this));	
		$this->ci =& get_instance();	
		
		$this->ci->load->model("Node_model", "Node");
		
		$this->addStatic("style", "ctypes.css");
	}
	
	function setName($name){
		$this->name = $name;
	}
	
	function getName(){
		return $this->name;
	}
	
	function addProperty($name, $value){
		$this->properties[$name] = $value;
	}
	
	function getProperty($name){
		if(isset($this->properties[$name])){
			return $this->properties[$name];
		}
		
		return FALSE;
	}
	
	function addProperties($properties){
		if($properties != NULL){
			foreach($properties as $key=>$value){
				$this->addProperty($key, $value);
			}
		}
	}
	
	function getProperties(){
		return $this->properties;
	}
	
	function addStatic($type, $path){
		if(isset($this->static[$type])){
			//@TODO Comprobar si ya existe la libreria a añadir
			if(array_search($path, $this->static[$type]) === FALSE){
				array_push($this->static[$type], $path);
			}
		}
	}
	
	function addStatics($statics){
		$keys = array_keys($statics);
		foreach($keys as $key){
			$staticsTmp = $statics[$key];
			foreach($staticsTmp as $static){
				$this->addStatic($key, $static);
			}
		}
	}
	
	function getStatics(){
		return $this->static;
	}
	
	function getDefinition(){
		return $this->definition;
	}
	
	function addTypeElement($typeElement){
		if($typeElement != NULL){
			if(!isset($this->typeElements[$typeElement->getName()]) || $this->typeElements[$typeElement->getName()] = NULL){
				$this->typeElements[$typeElement->getName()] = $typeElement;
			} else{
				echo "El campo " . $typeElement->getName() . " se encuentra duplicado";
			}
		}
	}
	
	function getTypeElement($name){
		if(isset($this->typeElements[$name])){
			return $this->typeElements[$name];
		}
	
		return FALSE;
	}
	
	public function view($id = NULL){
		$referrer = $this->ci->session->userdata("referrer");
		
		$node = NULL;
		$data = NULL;
		if($id != NULL){
			$node = $this->ci->Node->get(array("id" => $id, "status" => "all"));
			if($node !== FALSE){
				if(isset($node->data)){
					$data = unserialize($node->data);
				}
			}
		}
		
		$fields = "";
		foreach($this->definition as $typeElementName=>$config){
			$typeElement = $this->getTypeElement($typeElementName);
			if($typeElement !== FALSE){
				
				$this->addStatics($typeElement->getStatics());
				
				if($node != NULL && $node !== FALSE){
					$dataTypeElement = NULL;
					if(isset($data[$typeElement->getName()])){
						$dataTypeElement = $data[$typeElement->getName()];
					}
					$fields .= $typeElement->view($node, $dataTypeElement);
				} else{
					$fields .= $typeElement->view();
				}
			} else{
				echo "<br/>El tipo $typeElementName no esta cargado";
			}
		}
		
		//Categorias
		$this->ci->load->model("Category_Model", "Categories");
		$categories = $this->ci->Categories->get(array("status" => "all"));
		$selected_categories = array();
		if($id != NULL){
			$selected_categories = $this->ci->Nodes->getCategories($id);
		}
		
		$metas = $this->ci->Nodes->getMeta($id);
		
		$name = $this->name;
		$properties = $this->properties;
		$static = $this->static;
			
		ob_start();
		eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($this->template, TRUE))));
		$view = ob_get_contents();
		@ob_end_clean();
		
		return $view;
	}
	
	function checkCorrectSave(){
		$this->ci->form_validation->set_rules('ctype', 'CTYPE', 'required');
		$this->ci->form_validation->set_rules('ctype_title', 'Titulo', 'required');
		$this->ci->form_validation->set_rules('ctype_url_name', 'Url Name', 'required');
		
		//Fechas... no son obligatorias
		$this->ci->form_validation->set_rules('ctype_date_publish');
		$this->ci->form_validation->set_rules('ctype_date_publish_time');
		$this->ci->form_validation->set_rules('ctype_date_expire');
		$this->ci->form_validation->set_rules('ctype_date_expire_time');
		
		$correct = FALSE;
		
		if($this->ci->form_validation->run()){
			$correct = TRUE;
		}	
		
		foreach($this->definition as $typeElementName=>$config){
			$typeElement = $this->getTypeElement($typeElementName);
			if($typeElement !== FALSE){
				$correct = $correct & $typeElement->checkCorrectSave();
			} else{
				echo "<br/>El tipo $typeElementName no esta cargado";
			}
		}
		
		return $correct;
	}
	
	
	
	//@TODO devolver TRUE, FALSE para identificar la accion
	function save($id=NULL){
		//echo "GUARDANDO TIPO: "; 
		//print_r($this);
		
		$node = NULL;
		$data = NULL;
		if($id != NULL){
			$node = $this->ci->Node->get(array("id" => $id, "status" => "all"));
			if($node !== FALSE){
				if(isset($node->data)){
					$data = unserialize($node->data);
				}
			}
		} else{
			//@TODO crear el contenido para pasar el id
			$id = $this->ci->Node->create(array(
				"user_created"	=> $this->ci->redux_auth->profile()->id, 
				"user_modified"	=> $this->ci->redux_auth->profile()->id, 
				"type"			=> $this->getName(), 
			));
			
			if($id !== FALSE){
				$node = $this->ci->Node->get(array("id" => $id, "status" => "all"));
			}
		}
		
		
		$dataType = array();
		
		//$this->ci->form_validation->set_rules('ctype', 'CTYPE', 'required');
		if($this->ci->form_validation->run()){
			$ctypeTitle = $this->ci->input->post("ctype_title");
			$ctypeUrlName = $this->ci->input->post("ctype_url_name");
			$ctypeUrlName = strtolower(url_title($ctypeUrlName));
			$ctypeStatus = $this->ci->input->post("ctype_status");
			
			//Trtamos las fechas de publicacion y expiracion
			$ctypeDatePublish = time();
			$ctypeDatePublishDate = $this->ci->input->post("ctype_date_publish");
			$ctypeDatePublishTime = $this->ci->input->post("ctype_date_publish_time");
			if($ctypeDatePublishDate != ""){
				if($ctypeDatePublishTime == ""){
					$ctypeDatePublishTime = "00:00";
				}
				
				$date = explode('/', $ctypeDatePublishDate);
				$hour = explode(":", $ctypeDatePublishTime);
				$ctypeDatePublish = mktime($hour[0], $hour[1], 0, $date[1], $date[0], $date[2]);
				
			}
			
			$ctypeDateExpire = null;
			$ctypeDateExpireDate = $this->ci->input->post("ctype_date_expire");
			$ctypeDateExpireTime = $this->ci->input->post("ctype_date_expire_time");
			if($ctypeDateExpireDate != ""){
				if($ctypeDateExpireTime == ""){
					$ctypeDateExpireTime = "00:00";
				}
				
				$date = explode('/', $ctypeDateExpireDate);
				$hour = explode(":", $ctypeDateExpireTime);
				$ctypeDateExpire = mktime($hour[0], $hour[1], 0, $date[1], $date[0], $date[2]);
				
			}
			
			if($id != NULL){
				$this->ci->Nodes->deleteCategories($id);
			}
			
			//Obtenemos las categorias seleccionadas
			$categorias = $this->ci->input->post("ctypes_categories");
			
			if($node != NULL){
				$this->ci->Nodes->addCategories($node->id, $categorias);
			}
			
			
			foreach($this->definition as $typeElementName=>$config){
				$typeElement = $this->getTypeElement($typeElementName);
				
				if($typeElement !== FALSE){
					$value = NULL;
					
					if($node != NULL && $node !== FALSE){
						$dataTypeElement = NULL;
						if(isset($data[$typeElement->getName()])){
							$dataTypeElement = $data[$typeElement->getName()];
						}
						$value = $typeElement->save($node, $dataTypeElement);
					} else{
						$value = $typeElement->save();
					}
					
					if($value != NULL){
						$dataType[$typeElement->getName()] = $value;
					}
					
				} else{
					echo "<br/>El tipo $typeElementName no esta cargado";
				}
			}
			
			//@TODO update del contenido que se esta editando o creando..
			if($id  != NULL && $id !== FALSE){

				$id = $this->ci->Node->update(array(
					"id" 			=> $id, 
					"url_name"		=> $ctypeUrlName, 
					"language"		=> "es", 
					"status"		=> $ctypeStatus, 
					"user_created"	=> $this->ci->redux_auth->profile()->id, 
					"user_modified"	=> $this->ci->redux_auth->profile()->id, 
					"type"			=> $this->getName(), 
					"title"			=> $ctypeTitle, 
					"publish"		=> $ctypeDatePublish,
					"expiration"	=> $ctypeDateExpire,
					"data"			=> serialize($dataType)
				));
			}
		}
		
		return $node;
	}
	
	//@TODO devolver TRUE, FALSE para identificar la accion
	function delete($id = NULL){
		$node = NULL;
		$data = NULL;
		if($id != NULL){
			$node = $this->ci->Node->get(array("id" => $id, "status" => "all"));
			if($node !== FALSE){
				if(isset($node->data)){
					$data = unserialize($node->data);
				}
			}
		} 
		
		
		if($node !== FALSE && $node != NULL){
			foreach($this->definition as $typeElementName=>$config){
				$typeElement = $this->getTypeElement($typeElementName);
				
				if($typeElement !== FALSE){
					
					$dataTypeElement = NULL;
					if(isset($data[$typeElement->getName()])){
						$dataTypeElement = $data[$typeElement->getName()];
					}
					$correctDelete = $typeElement->delete($node, $dataTypeElement);
					
				} else{
					echo "<br/>El tipo $typeElementName no esta cargado";
				}
			}
			
		}
		
		//DELETE del node
		$this->ci->Node->delete($id);
		
		
		return $node;
	}
}
?>
